import dictService from "@/api/services/system/dictService";
import { create } from "zustand";

interface DictionaryState {
	dictionaries: Record<string, any>;
	loading: boolean; // 添加 loading 状态
	setDictionary: (code: string, items: any[]) => void;
	setLoading: (loading: boolean) => void; // 设置 loading 状态
	refreshDictionary: (code: string) => void;
	clearDictionary: () => void; // Method to clear all dictionaries
}

export const useDictionaryStore = create<DictionaryState>((set) => ({
	dictionaries: {},
	loading: false, // 初始化 loading 为 false
	setDictionary: (code, items) =>
		set((state) => ({
			dictionaries: { ...state.dictionaries, [code]: items },
		})),
	setLoading: (loading) => set({ loading }), // 设置 loading 状态
	refreshDictionary: async (code) => {
		try {
			set({ loading: true }); // 开始加载时，设置 loading 为 true
			const data = await dictService.getItemByCode(code);
			// 格式化字典数据
			const formattedData = data.map((item: { itemText: string; itemValue: string; color: string }) => ({
				label: item.itemText,
				value: item.itemValue,
				color: item.color,
			}));
			set((state) => ({
				dictionaries: {
					...state.dictionaries,
					[code]: formattedData,
				},
				loading: false, // 加载完成后，设置 loading 为 false
			}));
		} catch (error) {
			console.error("Failed to fetch dictionary", error);
			set({ loading: false }); // 如果发生错误，也需要设置 loading 为 false
		}
	},
	clearDictionary: () => set({ dictionaries: {}, loading: false }), // Clears all dictionaries
}));
